package cn.yx.application.gateway.filter;

import cn.hutool.core.util.StrUtil;
import cn.yx.application.gateway.util.GatewayUtil;
import cn.yx.common.core.constant.MdcConstant;
import cn.yx.common.core.enums.http.HttpHeaderCustomEnum;
import cn.yx.common.core.util.IdUtil;
import cn.yx.common.webflux.util.WebFluxUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * <p>GatewayLoggerFilter，用于获取网关请求的URL和原始URL，并打印日志，日志中包含自定义的traceId和SkyWalking的tid。</p>
 * <p>从网关请求记录的traceId可快速找到SkyWalking的tid，从而方便完整的链路追踪。</p>
 *
 * @author Wgssmart
 */
@Component
@Order(-10)
@Slf4j
public class GatewayLoggerFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String url = request.getURI().getPath();
        HttpHeaders httpHeaders = request.getHeaders();
        boolean transactionIdFromHeader = true;
        String transactionId = httpHeaders.getFirst(HttpHeaderCustomEnum.TRANSACTION_ID.getName());
        if (StrUtil.isEmpty(transactionId)) {
            transactionIdFromHeader = false;
            transactionId = IdUtil.id();
        }
        MDC.put(MdcConstant.TRACE_ID, transactionId);
        log.info("gateway request url: {}, {}", GatewayUtil.originalUrl(exchange), url);
        if (transactionIdFromHeader) {
            // 如果transactionId来源于请求头，则不需要重新构建请求头
            return chain.filter(exchange);
        }
        // 构建请求头，把生成的TransactionId放入请求头
        ServerHttpRequest serverHttpRequest = WebFluxUtil.addHeader(request, HttpHeaderCustomEnum.TRANSACTION_ID.getName(), transactionId);
        return chain.filter(exchange.mutate().request(serverHttpRequest).build());
    }

}
